package top.oylan.manager.jmsLiidtener;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.stereotype.Component;
import top.oylan.manager.entity.Section;
import top.oylan.manager.service.SectionService;
import top.oylan.manager.tools.SystemConstants;

import java.io.File;
import java.util.Date;
import java.util.List;

/**
 * @Author abduahad
 * @Description ${description}
 * @Date 2019-03-30
 */
@Component
public class VideoUpdateReceiver {

    @Autowired
    SectionService sectionService;

    @JmsListener(destination = "queue.update_section_video")
    public void videoUpdate(String message){

        JSONObject jsonObject = JSONObject.parseObject(message);
        JSONArray videos = jsonObject.getJSONArray("videos");

        Section condition = new Section();
        condition.setProductId(jsonObject.getInteger("productId"));
        condition.setParentId(jsonObject.getInteger("id"));
        List<Section> list = sectionService.selectSectionsByCondition(condition);

        for (Section sec:list){
            Section temp = new Section();
            for (int i = 0;i<videos.size();i++){
                JSONObject video = (JSONObject) videos.get(i);
                if(video.getInteger("id") == sec.getId()) {
                    // 修改
                    temp.setId(sec.getId());
                    temp.setVedioUrl(video.getString("url"));
                    temp.setTitle(video.getString("title"));
                    if(video.getInteger("num")!=null){
                        temp.setNum(video.getInteger("num"));
                    }
                    sectionService.update(temp);
                }
            }
            if(temp.getId() == null){
                // 删除
                File file = new File(SystemConstants.UPLOAD_ROOT_PATH+sec.getVedioUrl());
                if(file.exists()){
                    file.delete();
                }
                sectionService.delete(sec.getId());
            }
        }

        // 新增
        for (int i = 0;i<videos.size();i++){
            JSONObject opt = (JSONObject) videos.get(i);
            if(opt.getInteger("id") == 0){
                Section secVideo  = new Section();
                secVideo.setCreateTime(new Date());
                secVideo.setProductId(condition.getProductId());
                secVideo.setParentId(condition.getParentId());
                secVideo.setVedioUrl(opt.getString("url"));
                secVideo.setLv((byte)2);
                secVideo.setTitle(opt.getString("title"));
                if(opt.getInteger("num")!=null){
                    secVideo.setNum(opt.getInteger("num"));
                }
                sectionService.saveSection(secVideo);
            }
        }

    }
}
